﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Wise.Util
{
    /// <summary>
    /// 类型操作的扩展
    /// </summary>
    public static class TypeExtensions
    {
        /// <summary>
        /// 将可空类型解压成基础值类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Type UnpackNullableType(Type type)
        {
            if (!IsNullableType(type)) return type;
            return type.GetGenericArguments().FirstOrDefault() ?? type;
        }


        /// <summary>
        /// 将可空类型解压成基础值类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Type Unpack(this Type type)
        {
           return  UnpackNullableType(type);
        }

        /// <summary>
        /// 判断是否是可空类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool IsNullableType(this Type type)
        {
            if (type == null) throw new ArgumentNullException();
            if (!type.IsValueType) return false;
            return (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
        }
    }
}
